package com.example.demo.paper.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.example.demo.utils.CacheProvider;
import com.example.demo.exception.ZException;
import com.example.demo.answers.entity.TAnswers;
import com.example.demo.answers.service.ITAnswersService;
import com.example.demo.base.BaseController;
import com.example.demo.enums.ErrorEnum;
import com.example.demo.paper.entity.TPaper;
import com.example.demo.paper.service.ITPaperService;
import com.example.demo.paper_answer.entity.RPaperAnswer;
import com.example.demo.paper_answer.service.IRPaperAnswerService;
import com.example.demo.questions.service.ITQuestionsService;
import com.example.demo.utils.Result;
import com.example.demo.utils.ZUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 试卷表 前端控制器
 * </p>
 *
 * @author zhongz
 * @since 2019-02-16
 */
@Api(value = "试卷", description = "试卷操作 API", position = 100, protocols = "http")
@RestController
@RequestMapping("/paper/t-paper")
public class TPaperController extends BaseController {

    @Resource
    private ITAnswersService answersService;

    @Resource
    private ITQuestionsService questionsService;

    @Resource
    private ITPaperService paperService;

    @Resource
    private IRPaperAnswerService paperAnswerService;

    /**
     * 生成试卷
     *
     * @param num 题目数
     * @param uid 用户id
     * @return 试卷内容
     */
    @ApiOperation(
            value = "value",
            notes = "生成试卷",
            produces="application/json, application/xml",
            consumes="application/json, application/xml",
            response = Map.class)
    @GetMapping("/createPaper")
    public Map<String, Object> createPaper(@RequestParam(required = false) Integer num, String uid) {
        int NUM = 10;
        num = num == null ? NUM : num;
        List<Map<String, Object>> questionList = questionsService.listMaps(null);
        Integer max = questionList.size();
        if (num >= max) {
            num = max;
        }
        // 获取随机数组用于选取随机考题
        ArrayList<Integer> diffNO = ZUtils.getDiffNO(max, num);
        List<Map<String, Object>> records = new ArrayList<>();
        diffNO.parallelStream().forEach(i -> {
            records.add(questionList.get(i));
        });
        TPaper testPaper = new TPaper();
        testPaper.setId(ZUtils.getUUID());
        testPaper.setUserId(uid);
        testPaper.setTotalCount(num);
        testPaper.setCreateDatetime(ZUtils.getNowDateTimeStr());
        List<Map<String, Object>> results = this.transList(records, testPaper.getId());
        // 保存试卷数据
        paperService.save(testPaper);

        Map<String, Object> model = new HashMap<>();
        model.put("paperId", testPaper.getId());
        model.put("total", num);
        model.put("records", results);
        return success(model);
    }

    /**
     * 提交试卷
     *
     * @param paperId    试卷id
     * @param records    答题记录
     * @param rightCount 正确数
     * @param wrongCount 错误数
     * @param spendTime  花费时间
     * @return 结果
     */
    @PostMapping("/finishPaper")
    public Map<String, Object> finishPaper(String paperId, String records, Integer rightCount, Integer wrongCount,
                                           @RequestParam(required = false) Integer spendTime) {
        if (StringUtils.isEmpty(paperId) || StringUtils.isEmpty(records) || rightCount == null || wrongCount == null) {
            return fail(ErrorEnum.LACK_PARAM.getValue());
        }
        try {
            paperService.finishPaper(paperId, records, rightCount, wrongCount, spendTime);
            return success("提交成功");
        } catch (Exception e) {
            e.printStackTrace();
            return fail("提交失败");
        }
    }

    /**
     * 提交试卷（PC端）
     *
     * @param paperId    试卷id
     * @param records    答题记录
     * @param rightCount 正确数
     * @param wrongCount 错误数
     * @param spendTime  花费时间
     * @return 结果
     */
    @PostMapping("/finishPaper/PC")
    public Map<String, Object> finishPaperPC(String paperId, String records, Integer rightCount, Integer wrongCount,
                                             @RequestParam(required = false) Integer spendTime) {
        if (StringUtils.isEmpty(paperId) || StringUtils.isEmpty(records) || rightCount == null || wrongCount == null) {
            return fail(ErrorEnum.LACK_PARAM.getValue());
        }
        try {
            records = URLDecoder.decode(records, "UTF8");
            paperService.finishPaper(paperId, records, rightCount, wrongCount, spendTime);
            // 提交成功后，删除当前试卷的缓存信息
            CacheProvider.del("cachePaper");
            return success("提交成功");
        } catch (Exception e) {
            e.printStackTrace();
            return fail("提交失败");
        }
    }

    /**
     * 获取列表
     *
     * @param pagination 页码
     * @param size       每页显示数
     * @return 数据
     */
    @GetMapping("/list")
    public Map<String, Object> list(Integer pagination, Integer size) {
        IPage<Map<String, Object>> paperIPage = paperService.getList(pagination, size);
        return success(paperIPage);
    }

    /**
     * 缓存回答试卷数据
     *
     * @param paperId 试卷id
     * @param records 回答数据
     * @return
     */
    @PostMapping("/cachePaper")
    public Map<String, Object> cachePaper(String paperId, String records) {
        paperService.cachePaper(paperId, records);
        return success();
    }

    /**
     * 获取缓存的试卷数据
     *
     * @return
     */
    @GetMapping("/cachePaper")
    public Map<String, Object> getCachePaper() {
        Map model = CacheProvider.get("cachePaper", Map.class);
        if (model != null) {
            // 获取试卷id
            String paperId = (String) model.get("paperId");
            // 获取已答数据
            List<Map> list = JSON.parseArray((String) model.get("records"), Map.class);
            // 获取试卷数据
            try {
                List<Map<String, Object>> paperDetail = paperService.getDetail(paperId);
            } catch (ZException e) {
                return fail(e.getMessage());
            }
        }
        return success(model);
    }

    /**
     * 获取试卷详细内容
     *
     * @param id 试卷id
     * @return 试卷详细内容
     */
    @GetMapping("/detail/{id}")
    public Result detail(@PathVariable String id) {
        Result result = new Result();

        try {
            List<Map<String, Object>> detail = paperService.getDetail(id);
            result.setModel(detail);
        } catch (ZException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 完善list中的内容，用于前台展示
     *
     * @param questionList
     * @return
     */
    private List<Map<String, Object>> transList(List<Map<String, Object>> questionList, String paperId) {
        questionList.parallelStream().forEach(map -> {
            // 通过考题id查询对应的答案
            QueryWrapper<TAnswers> answersQueryWrapper = new QueryWrapper<>();
            answersQueryWrapper.eq("QUESTION_ID", map.get("id"));
            List<TAnswers> answersList = answersService.list(answersQueryWrapper);
            List<TAnswers> records = new ArrayList<>();
            // 获取随机数组用于随机展示答案
            ArrayList<Integer> diffNO = ZUtils.getDiffNO(answersList.size());
            for (int i = 0; i < answersList.size(); i++) {
                // 查询答案信息
                TAnswers answers = answersList.get(diffNO.get(i));
                records.add(answers);
                if (StringUtils.equals(map.get("rightAnswerId").toString(), answers.getId())) {
                    map.put("rightAnswer", answers.getAnsContent());
                }
            }
            map.put("answerList", records);
            // 向试卷与考题关系表中插入数据
            RPaperAnswer paperAnswer = new RPaperAnswer();
            paperAnswer.setId(ZUtils.getUUID());
            paperAnswer.setPaperId(paperId);
            paperAnswer.setQuestionId(map.get("id").toString());
            paperAnswerService.save(paperAnswer);
        });
        return questionList;
    }
}
